package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.*;
import worklog.dto.ProjectDTO;
import worklog.dto.ResponseDTO;

@WebServlet("/updateProject")
public class UpdateProject extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProjectDB projectDB;
	private ResponseDTO responder = new ResponseDTO();

    public UpdateProject() { super(); }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		projectDB = new ProjectDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	out.print(processRequest(request));
    	projectDB.close();
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
		HttpSession session = request.getSession();
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		int userId = (Integer) session.getAttribute("userId");

		int paramLength = request.getParameterMap().size(), projectId, res;
		String name, tags, id, isFavStr, archiveStr;
		Boolean isFav, archive;
		ProjectDTO project = new ProjectDTO();
        
    	if (paramLength > 0) {
			id = request.getParameter("id");
			name = request.getParameter("name");
			archiveStr = request.getParameter("archive");
			tags = request.getParameter("tags");
			isFavStr = request.getParameter("isFav");
			
			if (id == null) return responder.showError("Project ID is empty"); 
			if (name == null && tags == null) return responder.showError("There is nothing to edit...");
			
			try{ projectId = Integer.parseInt(id); }
			catch(NumberFormatException e){ projectId = -1; }
			if (projectId == -1) return responder.showError("Incorrect projet ID");
			
			project = projectDB.getProject(projectId, userId);
			if (project == null) return responder.showError("Project does not exist");
			
			if (name != null) project.setName(name);
			if (tags != null) project.setTags(tags);
			if (archiveStr != null) {
				archive = archiveStr.equals("true");
				project.setArchive(archive);
			}
			if (isFavStr != null){
				isFav = isFavStr.equals("true");
				project.setIsFav(isFav);
			}
			
			res = projectDB.updateProject(project, userId);
			if (res == -1) return responder.showError("DB error");
			else return project.toString();
    	}	
		return responder.showError();
	}
}
